﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.PropertyTypes;
using System.Web.Mvc;
using Newtonsoft.Json;
using Proggy.Web.Cms.Core.Configuration.ConfigObjects;

namespace Proggy.Web.Cms.Core.PropertyTypes
{
    /// <summary>
    /// 
    /// </summary>
    [PropertyType("Enum drop down list", "~/Areas/ProggyCore/Views/EditorPartials/DropDown.cshtml", RequiredConfigObjectType = typeof(DropDownConfigObject))]
    public class DropDown : ConfigurablePropertyTypeBase, IValidatablePropertyType
    {
        /// <summary>
        /// Set the items
        /// </summary>
        /// <param name="t"></param>
        public void SetItems(DropDownConfigObject configObject)
        {
            // set type
            this._data = configObject.Data;

            // check if enum
            if (this._data.Count() <1)
            {
                throw new Exception("Data has no values");
            }

            // set
            this._dropDownListItems =
                this._data.Select(x => new SelectListItem
                {
                    Text = x.Key,
                    Value = x.Value,
                    Selected = this.SavedValue == null ? false : this.SavedValue == x.Value
                });            
        }

        /// <summary>
        /// Data - key = text, value = value
        /// </summary>
        [JsonIgnore]
        public IEnumerable<KeyValuePair<string,string>> Data { get { return this._data; } }
        private IEnumerable<KeyValuePair<string, string>> _data;

        /// <summary>
        /// Drop down list
        /// </summary>
        [JsonIgnore]
        public IEnumerable<SelectListItem> DropDownListItems { get { return this._dropDownListItems; } }
        private IEnumerable<SelectListItem> _dropDownListItems;

        /// <summary>
        /// Saved value
        /// </summary>
        public string SavedValue { get; set; }

        /// <summary>
        /// Validation
        /// </summary>
        /// <param name="vContext"></param>
        /// <param name="attr"></param>
        /// <returns></returns>
        public Tuple<bool, string> GetIsValid(System.ComponentModel.DataAnnotations.ValidationContext vContext, ContentModel.ContentModelPropertyTypeAttribute attr)
        {
            return new Tuple<bool, string>(true, "");
        }
    }
}
